<!-- 采购管理-采购订单列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="jump">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>新建采购订单</template>
      </a-button>
    </template>
  </pageHeader>
  <div>
    <a-tabs @change="searchState" type="line">
      <a-tab-pane :key="0" title="全部采购订货单"> </a-tab-pane>
      <a-tab-pane :key="1" title="我的采购订货单"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <!-- <a-input-search
            @change="search"
            :style="{ width: 'auto' }"
            placeholder="请输入"
            v-model="currSelectSearch"
          >
            <template #prefix>
              <a-select
                :style="{ width: '120px', marginRight: '10px' }"
                placeholder="请选择"
                v-model="currSelectVal"
              >
                <a-option value="number">采购订单单号</a-option>
              </a-select>
            </template>
          </a-input-search> -->
        <a-input-group>
          <!-- <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="number">采购订单单号</a-option>
          </a-select> -->
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入采购订单单号"
            @search="search"
            v-model="currSelectSearch"
          />
        </a-input-group>
        <div>
          <a-select placeholder="请选择" v-model="userState" @change="search">
            <template #prefix>状态：</template>
            <a-option :value="1">待执行</a-option>
            <a-option :value="2">执行中</a-option>
            <a-option :value="3">已完成</a-option>
            <a-option :value="0">全部</a-option>
          </a-select>
        </div>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.name"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.code"
        align="center"
        :width="150"
        :sortable="{
          sortDirections: ['ascend', 'descend'],
        }"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <!-- 申请明细  -->
        <template v-if="item.code === 'applyDetail'" #cell="{ record }">
          <a-typography-text type="primary" @click="See(record.product)">
            查看
          </a-typography-text>
        </template>

        <!-- 申请原因 -->
        <template v-else-if="item.code === 'applyCause'" #cell="{ record }">
          <a-typography-text type="primary" @click="view(record.cause)">
            查看
          </a-typography-text>
        </template>
        <!-- 订单创建时间 -->
        <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
          {{
            record.createdAt
              ? dayjs(record.createdAt).format('YYYY-MM-DD')
              : '无'
          }}
        </template>

        <!-- 交付日期 -->
        <template v-else-if="item.code === 'delivery_time'" #cell="{ record }">
          {{ dayjs(record.applyTime).format('YYYY-MM-DD') }}
        </template>

        <!-- 关联申请单号 -->
        <template v-else-if="item.code === 'applyNumber'" #cell="{ record }">
          <a-typography-text v-if="!record.applyNumber" type="secondary">
            无
          </a-typography-text>
          <a-typography-text v-else type="success">
            {{ record.applyNumber }}
          </a-typography-text>
        </template>

        <!-- 关联计划单号 -->
        <template v-else-if="item.code === 'planNumber'" #cell="{ record }">
          <a-typography-text v-if="!record.planNumber" type="secondary">
            无
          </a-typography-text>
          <a-typography-text v-else type="success">
            {{ record.planNumber }}
          </a-typography-text>
        </template>

        <!-- 关联申请单号 -->
        <template v-else-if="item.code === 'taskNumber'" #cell="{ record }">
          <a-typography-text v-if="!record.taskNumber" type="secondary">
            无
          </a-typography-text>
          <a-typography-text v-else type="success">
            {{ record.taskNumber }}
          </a-typography-text>
        </template>

        <!-- 优先级 -->
        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <!-- 审核状态 -->
        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderExamineStatus.filter(
                (ele) => ele.id === record.state
              )[0]?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderExamineStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{
              orderExamineStatus.filter((ele) => ele.id === record.state)[0]
                ?.value
            }}
          </div>
        </template>

        <!-- 状态 -->
        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="150" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <!-- {{ rowIndex + 1 }} -->
          <!-- <div v-if="saveUserId.id === record.salesman"> -->
          <a-space v-if="record.state === 1">
            <!-- <a-button type="primary" status="success"
              >提交审核</a-button
            >
            <a-button type="text" >进入详情</a-button>
            <a-popconfirm content="确认删除?" type="error" >
              <a-button type="text" status="danger">删除</a-button>
            </a-popconfirm> -->
            <a-tooltip content="提交审核">
              <IconFont
                type="icon-tijiaoshenhe1"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="Submit(record)"
              />
            </a-tooltip>

            <a-tooltip content="进入详情">
              <IconFont
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="edit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除">
              <a-popconfirm
                content="确认删除？"
                type="error"
                @ok="del(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>

          <a-tooltip
            v-else-if="
              record.state === 4 || record.state === 6 || record.state === 7
            "
            content="订单档案"
          >
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goFile(record.id)"
            />
          </a-tooltip>
          <a-tooltip v-else content="进入详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="edit(record.id)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="采购订单列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <qrcode v-model:visible="qrcodeVisible" :qrId="qrcodeId"></qrcode>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchaseOrderList,
    putSinglePurchaseOrder,
    delPurchaseOrderList,
  } from '@/api/buy-management/buy-order/index';

  const router = useRouter();
  const title: string = '采购订单列表';
  const breadCrumb: string[] = ['采购管理', '采购管理', '采购订单列表'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const beginTime = ref();
  const endTime = ref();
  const qrcodeId = ref();
  const qrcodeVisible = ref(false);
  const modelCauseVisible = ref(false);
  const userState = ref();

  const orderExamineStatus = [
    { id: 1, value: '待提交', backgroundColor: '#cccccc' },
    { id: 2, value: '待审核', backgroundColor: '#cccccc' },
    { id: 3, value: '审核中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '已通过', backgroundColor: '#009933' },
    { id: 5, value: '不通过', backgroundColor: '#009933' },
    { id: 6, value: '已通过', backgroundColor: '#009933' },
  ];

  const orderStatus = [
    { id: 1, value: '待执行', backgroundColor: '#cccccc' },
    { id: 2, value: '待执行', backgroundColor: '#cccccc' },
    { id: 3, value: '待执行', backgroundColor: '#cccccc' },
    { id: 4, value: '执行中', backgroundColor: '#4e8bfb' },
    { id: 5, value: '待执行', backgroundColor: '#4e8bfb' },
    { id: 6, value: '已完成', backgroundColor: '#009933' },
    { id: 7, value: '异常完成', backgroundColor: '#4e8bfb' },
  ];
  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive({
    list: [],
  });
  const saveUserId = ref();
  saveUserId.value = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const applyByUser = ref();

  // 表格配置
  const args = reactive({
    stripe: true,
    // scroll: {
    //   y: 500,
    // },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const columns = [
    { code: 'number', isDefault: 1, name: '采购订单编号' },
    { code: 'supplierName', isDefault: 1, name: '供应商名称' },
    { code: 'phone', isDefault: 1, name: '联系电话' },
    { code: 'salesmanName', isDefault: 1, name: '业务员' },
    { code: 'totalPrice', isDefault: 1, name: '采购总金额' },
    { code: 'createdAt', isDefault: 1, name: '订单创建时间' },
    { code: 'planNumber', isDefault: 1, name: '关联采购计划单号' },
    { code: 'taskNumber', isDefault: 1, name: '关联采购任务单号' },
    { code: 'okState', isDefault: 1, name: '审核状态' },
    { code: 'state', isDefault: 1, name: '状态' },
    { code: 'contactMan', isDefault: 2, name: '联系人' },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };
  // 获取表头设置
  const headerSettingData = async () => {
    try {
      const res = await getPurchaseHeader({ userId: 317, listType: 6 });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const onChange = (value: any) => {
    if (value !== undefined) {
      beginTime.value = value[0];
      endTime.value = value[1];
      tableRef.value.loadData();
    } else {
      tableRef.value.loadData();
    }
  };
  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (applyByUser.value) msg.applyByUser = applyByUser.value;
      if (beginTime.value) msg.beginTime = beginTime.value;
      if (endTime.value) msg.endTime = endTime.value;
      const res = await getPurchaseOrderList({
        ...pageData,
        ...msg,
      });
      if (res.content === null && res.content === undefined) {
        res.content = [];
      }
      return res;
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const jump = () => {
    if (sessionStorage.getItem('store')) {
      sessionStorage.removeItem('store');
    }
    router.push({
      name: 'AddOrderPurchaseList',
    });
  };

  const goQrcode = (id?: number) => {
    qrcodeVisible.value = true;
    qrcodeId.value = id;
  };

  const searchState = (key: any) => {
    if (key === 1) {
      let into = JSON.parse(sessionStorage.getItem('loginInfo') as any);
      applyByUser.value = into.id;
      tableRef.value.refreshPaging();
      tableRef.value.loadData();
    } else {
      applyByUser.value = null;
      tableRef.value.refreshPaging();
      tableRef.value.loadData();
    }
  };

  const del = async (id: number) => {
    await delPurchaseOrderList({ id });
    reset();
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: 317,
        listType: 6,
        extend: JSON.stringify(val),
      };
      await PUTPurchaseHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeCauseDate = ref();
  const view = (content: string) => {
    SeeCauseDate.value = content;
    modelCauseVisible.value = true;
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });
  const SeeDate = ref();
  const See = (item: any) => {
    modelVisible.value = true;
    SeeDate.value = item;
  };

  // 提交审核
  const Submit = async (data: any) => {
    data.state = 3;
    await putSinglePurchaseOrder(data);
    reset();
  };

  const edit = (id: number) => {
    router.push({
      name: 'EditOrderPurchaseList',
      query: { id },
    });
  };

  const goFile = (id: number) => {
    router.push({
      name: 'EditOrderFile',
      query: { id },
    });
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }
</style>
